<template>
  <TopBar></TopBar>
  <div class="body">
    <div class="chat-container">
      <el-row>
        <!-- 用户搜索和列表 -->
        <el-col :span="4">
          <el-card class="user-list-card">
            <div style="color: #296D10; font-size: 2.5vh;" class="user-list-header">
              用户列表
              <span class="user-list-subtext">（点击开始聊天）</span>
            </div>
            <div>
              <el-input v-model="searchKeyword" placeholder="搜索用户" @input="searchUsers">
                <template #append>
                  <el-button icon="el-icon-search" @click="searchUsers"></el-button>
                </template>
              </el-input>
            </div>
            <!-- 添加好友按钮 -->
            <el-button type="primary" @click="showAddFriendDialog = true" style="width: 100%; margin-top: 10px;">
              添加好友
            </el-button>
            <!-- 好友列表 -->
            <div class="user-list-controller">
              <div v-for="user in filteredUsers" :key="user.username" class="user-list-item"
                @click="selectChatUser(user.username)" :class="{ selected: user.username === chatUser }">
                <v-avatar :image="getAvatar(user.username)" style="margin-left: 1vh;"></v-avatar>
                <span style="margin-left: 1vh;">{{ getName(user.username) }}</span>
                <span v-if="user.username === chatUser" class="chatting-indicator">聊天中...</span>
                <div v-if="user.username === chatUser" class="select_color"
                  style="display: flex; position: absolute;background-color: orangered;width: 0.5vh;height: 6.5vh;margin-top: -5.4vh;">
                </div>
              </div>
            </div>

          </el-card>
        </el-col>

        <!-- 聊天窗口 -->
        <el-col :span="20">
          <div class="chat-box">
            <div class="chat-header">{{ chatHeader }}</div>
            <div class="chat-content">
              <div v-if="chatUser">
                <div v-for="msg in currentChatMessages" :key="msg.timestamp"
                  :class="msg.user === user.username ? 'self-message' : 'other-message'">
                  <div v-if="msg.user !== user.username" class="message-avatar">
                    <v-avatar :image="getAvatar(msg.user)" class="avatar"></v-avatar>
                  </div>
                  <div class="message-bubble">
                    <span>{{ msg.text }}</span>
                    <div class="message-timestamp">{{ formatTimestamp(msg.timestamp) }}</div>
                  </div>
                  <div v-if="msg.user === user.username" class="message-avatar">
                    <v-avatar :image="getAvatar(msg.user)" class="avatar"></v-avatar>
                  </div>
                </div>
              </div>
              <div v-else>
                <p>请先选择一个好友进行聊天。</p>
              </div>
            </div>

            <div class="chat-input-box" v-if="chatUser">
              <textarea v-model="text" class="chat-input"></textarea>
              <el-button style="width: 10%;height: 20%;margin-left: auto" type="primary" size="small"
                @click="send">发送</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <Footer></Footer>

    <!-- 添加好友对话框 -->
    <el-dialog v-model="showAddFriendDialog" title="添加好友" width="30%">
      <el-input v-model="friendSearchKeyword" placeholder="搜索用户" style="margin-bottom: 10px;"></el-input>
      <div v-for="user in allUsers" :key="user.username" class="user-list-item" @click="addFriend(user.username)">
        <v-avatar :image="getAvatar(user.username)" style="margin-left: 1vh;"></v-avatar>
        <span style="margin-left: 1vh;">{{ getName(user.username) }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import TopBar from '@/component/TopBar.vue';
import Footer from '@/component/Footer.vue';
import { ElMessage } from "element-plus";
import request from '../../utils/request';
import { Watch } from 'lucide-vue-next';

const user_list = ref([]);
const chatUser = ref('');
const text = ref('');
const messages = reactive({});
const socket = ref(null);
const user = ref({});
const searchKeyword = ref('');
const showAddFriendDialog = ref(false); // 控制添加好友对话框的显示
const friendSearchKeyword = ref(''); // 添加好友搜索关键词


const getAvatar = (username) => {
  const item = user_list.value.find(item => item.username === username);
  return item ? item.avatar : 'default_avatar_url';
}

const getName = (username) => {
  const item = user_list.value.find(item => item.username === username);
  return item ? item.name : 'error';
}

const currentChatMessages = computed(() => {
  if (!chatUser.value) return [];
  const userPair = [user.value.username, chatUser.value].sort().join('_');
  return messages[userPair] || [];
});


const chatHeader = computed(() => {
  return `叽喳聊天（${chatUser.value || '请选择聊天对象'}）`;
});

const filteredUsers = computed(() => {
  // 获取所有与当前用户有过聊天记录的好友
  const chatPartners = new Set();
  for (const userPair in messages) {
    const [user1, user2] = userPair.split('_');
    if (user1 === user.value.username) {
      chatPartners.add(user2);
    } else if (user2 === user.value.username) {
      chatPartners.add(user1);
    }
  }

  // 过滤出与当前用户有过聊天记录的好友
  return user_list.value.filter(u =>
    u.username !== user.value.username &&
    chatPartners.has(u.username)
  );//按用户名排序
});

const allUsers = computed(() => {
  // 过滤掉当前用户自己和已经添加的好友
  return user_list.value.filter(u =>
    u.username !== user.value.username &&
    !filteredUsers.value.some(friend => friend.username === u.username)
  );
});

onMounted(async () => {
  const uid = sessionStorage.getItem('uid');
  const uidObj = JSON.parse(uid);
  const res = await request.get('/api/user/GetUserInfo', {
    params: {
      uid: uidObj
    }
  });
  user.value = res.data;
  console.log('Current user:', user.value);
  const tempUser = ref({});
  // 获取所有用户
  await request.get('/api/user/selectUserAll').then(res => {
    user_list.value = res.data;
    console.log('All users:', user_list.value);
  });

  // 获取所有农民用户
  await request.get('/farmer/selectFarmerAll').then(res => {
    console.log("获取所有农民用户");
    console.log(res.data);
    user_list.value.push(...res.data);
  });

  const username = res.data.username;
  const socketUrl = `ws://localhost:9090/imserver/${username}`;

  socket.value = new WebSocket(socketUrl);

  socket.value.onopen = () => {
    console.log("WebSocket已连接");
  };

  socket.value.onmessage = (msg) => handleIncomingMessage(msg);
  socket.value.onclose = () => console.log("WebSocket已关闭");
  socket.value.onerror = () => console.error("WebSocket发生错误");

  //监听filteredUsers的变化，当有新的聊天记录时，默认选择好友列表中的第一个好友进行聊天
  console.log(user_list.value.length);
    if(user_list.value.length > 0) {
      chatUser.value =user_list.value[0].username;
    }
    console.log("我是默认用户"+chatUser.value);

});

function updateChatWindow() {
  const chatBox = document.querySelector('.chat-content');
  chatBox.scrollTop = chatBox.scrollHeight;
}

function handleIncomingMessage(msg) {
  const data = JSON.parse(msg.data);
  if (data.users) {
    // 忽略在线用户列表更新
  } else {
    const userPair = [data.from, data.to].sort().join('_');
    if (!messages[userPair]) {
      messages[userPair] = [];
    }
    messages[userPair].push({
      user: data.from,
      text: data.text,
      timestamp: data.timestamp || new Date()
    });

    // 如果当前聊天对象是消息的发送者，更新聊天窗口
    if (data.from === chatUser.value) {
      updateChatWindow();
    }
  }
}

function formatTimestamp(timestamp) {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString();
}

function selectChatUser(username) {
  if (chatUser.value !== username) {
    chatUser.value = username;
  }
}

function send() {
  if (!chatUser.value || !text.value.trim()) {
    ElMessage({
      type: 'warning',
      message: !chatUser.value ? "请选择聊天对象" : "请输入内容"
    });
    return;
  }

  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    const message = { from: user.value.username, to: chatUser.value, text: text.value };
    socket.value.send(JSON.stringify(message));
    addMessageToChat(user.value.username, text.value, chatUser.value);
    text.value = '';
  } else {
    ElMessage({
      type: 'error',
      message: 'WebSocket未连接，无法发送消息'
    });
  }
}

function addMessageToChat(sender, text, chatUser) {
  const userPair = [sender, chatUser].sort().join('_');
  if (!messages[userPair]) {
    messages[userPair] = [];
  }
  messages[userPair].push({ user: sender, text, timestamp: new Date() });
}

// 添加好友
function addFriend(username) {
  if (!messages[`${user.value.username}_${username}`] && !messages[`${username}_${user.value.username}`]) {
    messages[`${user.value.username}_${username}`] = [];
  }
  showAddFriendDialog.value = false;
  selectChatUser(username);
}

// 搜索用户
function searchUsers() {
  if (searchKeyword.value.trim() === '') {
    return;
  }
  const chatPartners = new Set();
  for (const userPair in messages) {
    const [user1, user2] = userPair.split('_');
    if (user1 === user.value.username) {
      chatPartners.add(user2);
    } else if (user2 === user.value.username) {
      chatPartners.add(user1);
    }
  }

  // 过滤出与当前用户有过聊天记录的好友
  return user_list.value.filter(u =>
    u.username !== user.value.username &&
    (chatPartners.has(u.username) || u.username.includes(searchKeyword.value) || u.name.includes(searchKeyword.value))
  );
}
</script>

<style scoped>
.body {
  background-color: #F3F3F3;
}

.chat-container {
  padding: 5vh;
  margin-bottom: 50px;
}

.user-list-card {
  width: 100%;
  height: 100%;
  color: #333;
}

.user-list-header {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
}

.user-list-subtext {
  font-size: 12px;
}

.user-list-controller{
  height: 43vh;
  overflow: auto;
}

.user-list-item {
  padding: 10px 0;
  cursor: pointer;
}

.user-list-item.selected {
  background-color: #f0f0f0;
}

.user-list-item:hover {
  background-color: #e0e0e0;
}

.chatting-indicator {
  font-size: 12px;
  color: limegreen;
  margin-left: 5px;
}

.chat-box {
  width: 100%;
  margin: 0 auto;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 0 10px #ccc;
}

.chat-header {
  background-color: #296D10;
  color: white;
  text-align: center;
  font-weight: bold;
  font-size: 2vh;
  line-height: 8vh;
}

.chat-content {
  height: 43vh;
  overflow: auto;
  padding: 10px;
  border-top: 1px solid #ccc;
}

.chat-input-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ccc;
}

.chat-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.el-button {
  padding: 10px 20px;
}

.self-message,
.other-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.self-message {
  justify-content: flex-end;
}

.other-message {
  justify-content: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
}

.message-bubble {
  display: inline-block;
  position: relative;
  word-wrap: break-word;
  margin: 0 10px;
}

.self-message .message-bubble {
  background-color: #e0f7fa;
  color: black;
  border-radius: 10px;
  padding: 10px;
  max-width: 60%;
}

.other-message .message-bubble {
  background-color: #e8eaf6;
  color: black;
  border-radius: 10px;
  padding: 10px;
  max-width: 60%;
}

.message-timestamp {
  font-size: 10px;
  color: #888;
  text-align: right;
  margin-top: 5px;
}
</style>